package com.example.myapplication.ui

import AssetUtils
import android.Manifest
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.ActivityCompat
import org.vosk.Model
import org.vosk.Recognizer
import org.vosk.android.RecognitionListener
import org.vosk.android.SpeechService

@Composable
fun VoiceScreen() {
    val context = LocalContext.current
    var showDialog by remember { mutableStateOf(false) }
    var permissionGranted by remember { mutableStateOf(false) }
    val handler = remember { Handler(Looper.getMainLooper()) }
    var speechService by remember { mutableStateOf<SpeechService?>(null) }
    var model by remember { mutableStateOf<Model?>(null) }
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        permissionGranted = granted
        if (!granted) {
            Toast.makeText(context, "请授予麦克风权限以使用语音识别功能", Toast.LENGTH_LONG).show()
        }
    }

    LaunchedEffect(Unit) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            launcher.launch(Manifest.permission.RECORD_AUDIO)
        } else {
            permissionGranted = true
        }
    }

    LaunchedEffect(permissionGranted) {
        if (permissionGranted) {
            // 初始化 Vosk
            try {
                val path = AssetUtils.copyAssetToInternalStorage(context,"model")
                model = Model(path)
                val recognizer = Recognizer(model, 16000.0f)
                speechService = SpeechService(recognizer, 16000.0f)
                speechService?.startListening(object : RecognitionListener {
                    override fun onPartialResult(hypothesis: String?) {
                        if (hypothesis?.contains("小超", ignoreCase = true) == true) {
                            handler.post { showDialog = true }
                        }
                    }
                    override fun onResult(hypothesis: String?) {}
                    override fun onFinalResult(hypothesis: String?) {}
                    override fun onError(e: Exception?) {}
                    override fun onTimeout() {}
                })
            } catch (e: Exception) {
                Toast.makeText(context, "模型加载失败：${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }

    if (showDialog) {
        AlertDialog(
            onDismissRequest = { showDialog = false },
            title = { Text("唤醒词检测") },
            text = { Text("检测到唤醒词：小超") },
            confirmButton = {
                Button(onClick = { showDialog = false }) {
                    Text("确定")
                }
            }
        )
    }
} 